import { isURL } from '@/utils/validate'

/**
 *加密处理
 */
export const encryption = params => {
  let { data, type, param, key } = params
  const result = JSON.parse(JSON.stringify(data))
  if (type === 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele])
    })
  } else {
    param.forEach(ele => {
      let data = result[ele]
      /*eslint-disable*/
      key = CryptoJS.enc.Latin1.parse(key)
      let iv = key
      // 加密
      let encrypted = CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      })
      /* eslint-enable */
      result[ele] = encrypted.toString()
    })
  }
  return result
}

/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = ''
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substr(0, len || 4)
  if (date) random = random + Date.now()
  return random
}

// 生成随机字符串
export const randomString = len => {
  len = len || 32
  const $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789'
  const maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

export function compare (propertyName) {
  return function (object1, object2) {
    var value1 = object1[propertyName]
    var value2 = object2[propertyName]
    if (value2 < value1) {
      return 1
    } else if (value2 > value1) {
      return -1
    } else {
      return 0
    }
  }
}

export const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj (obj) {
  if (!(typeof obj === 'object')) {
    return
  }

  for (var key in obj) {
    if (obj.hasOwnProperty(key) && (obj[key] == null || obj[key] === undefined || obj[key] === '')) {
      delete obj[key]
    }
  }
  return obj
}

/**
 * 深度克隆对象、数组
 * @param obj 被克隆的对象
 * @return 克隆后的对象
 */
export function cloneObject (obj) {
  return JSON.parse(JSON.stringify(obj))
}

// 生成首页路由
export function generateIndexRouter (data) {
  let indexRouter = [
    {
      path: '/',
      component: resolve => require(['@/components/layouts/TabLayout'], resolve),
      redirect: data[0].menuRoute,
      children: [...generateChildRouters(data)]
    }
    // {
    //   path: '*',
    //   redirect: '/404',
    //   hidden: true
    // },
    // {
    //   path: '/404',
    //   hidden: true,
    //   component: resolve => require(['@/views/exception/404'], resolve)
    // }
  ]
  return indexRouter
}

// 生成嵌套路由（子路由）
export function generateChildRouters (data) {
  const routers = []
  for (let item of data) {
    let component = 'views/children' + item.menuRoute + '/index'

    // if (item.menuRoute === '/workOrder') {
    //   component = 'views/children' + '/WorkOrder' + '/index'
    // }
    // if (item.component.indexOf('layouts') >= 0) {
    //   component = 'components/' + item.component
    // } else {
    //   component = 'views/' + item.component
    // }
    // eslint-disable-next-line
    let URL = (item.dispatchUrl || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      item.url = URL
    }
    /**
     * 直接跳进第一个子菜单 现在注掉了。因为开发的时候不好用。liyi
     */
    // let hasChildren = item.children && item.children.length
    let menu = {
      path: item.menuRoute,
      name: item.menuRoute,
      // redirect: hasChildren ? item.menuRoute + item.children[0].url : '',
      component: resolve => require(['@/' + component + '.vue'], resolve),
      hidden: item.hidden,
      meta: {
        title: item.sceneName,
        icon: item.picUrl,
        url: item.url,
        sceneNo: item.sceneNo,
        pkId: item.pkId
      }
    }
    /**
     * 暂时放开这两个 模块加一个放一个 liyi
     */
    if (item.children && item.children.length > 0) {
      // if (item.menuRoute === '/patrol' || item.menuRoute === '/workOrder') {
      menu.children = [...generateChildChildRouters(item.children)]
      // }
    }
    routers.push(menu)
  }
  return routers
}

function generateChildChildRouters (data) {
  const routers = []
  for (let item of data) {
    let hasChildren = item.children && item.children.length
    if (item.parentId === '0') {
      item.name = item.menuName
      item.url = item.menuRoute
      item.frontPath = 'Layout/AppContent'
    }
    item.redirect = hasChildren ? item.children[0].url : ''
    // 首字母改成小写
    let component = 'views/children/' + replaceStr(item.frontPath)

    // if (item.frontPath.substr(0, 9) == 'WorkOrder') {
    //   component = 'views/children/' + item.frontPath
    // }
    // console.log(item.url.splice('/'))
    let menu = {
      path: item.url,
      name: item.url,
      hidden: item.isEnable === 0,
      sceneNo: item.sceneNo,
      pkId: item.pkId,
      // redirect: item.redirect,
      component: resolve => require([`@/${component}`], resolve),
      // component: () => import('@/views/children/patrol/TempTask'),
      // component: () => import(`@/${component}`),
      meta: {
        title: item.name,
        icon: item.picUrl,
        url: item.thdUrl,
        sceneNo: item.sceneNo,
        pkId: item.pkId
      }
    }
    if (hasChildren > 0) {
      menu.children = [...generateChildChildRouters(item.children)]
    }
    routers.push(menu)
  }
  return routers
}

function replaceStr (str) {
  let strTemp = '' // 新字符串
  for (let i = 0; i < str.length; i++) {
    if (i === 0) {
      strTemp += str[i].toLowerCase() // 第一个
      continue
    }
    if (str[i] === ' ' && i < str.length - 1) {
      // 空格后
      strTemp += ' '
      strTemp += str[i + 1].toLowerCase()
      i++
      continue
    }
    strTemp += str[i]
  }
  return strTemp
}

// 修正数字为两位数
export function returnFloat (valueObj) {
  var value = Math.round(parseFloat(valueObj) * 100) / 100
  if (!value) {
    return '0.00'
  }
  var s = value.toString().split('.')
  if (s.length === 1) {
    value = value.toString() + '.00'
    return value
  }
  if (s.length > 1) {
    if (s[1].length < 2) {
      value = value.toString() + '0'
    }
    return value
  }
}

// x为传入的值，pos为保留的小数位
export function fomatFloat (x, pos) {
  var f = parseFloat(x)
  if (isNaN(f)) {
    return false
  }
  f = Math.round(x * Math.pow(10, pos)) / Math.pow(10, pos) // pow 幂
  var s = f.toString()
  var rs = s.indexOf('.')
  if (rs < 0) {
    rs = s.length
    s += '.'
  }
  while (s.length <= rs + pos) {
    s += '0'
  }
  return s
}

// 年月日输出
export function timesToymd () {
  let date = new Date()
  let Y = date.getFullYear() + '年'
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月'
  let D = date.getDate() < 10 ? '0' + date.getDate() + '日' : date.getDate() + '日'
  let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return Y + M + D + ' ' + h + m + s
}

// 递归处理tree结构数据
export function recursionTree (result) {
  const treeData = []
  if (result && result.length !== 0) {
    result.map(item => {
      const obj = {
        value: item.areaId,
        label: item.areaName,
        children: []
      }
      if (item.hasOwnProperty('childs') && item.childs && item.childs.length !== 0) {
        obj.children = recursionTree(item.childs)
      }
      if (obj.children.length === 0) {
        delete obj.children
      }
      treeData.push(obj)
    })
  }
  return treeData
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  let event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}
